package networktool;

import bartenderqueue.DrinkButton;
import drinkkiosk.drinks.SpecialDrink;
import java.awt.Color;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;

/**
 * 
 * @author novaterata
 */
public class BartenderServer implements Runnable {
    private Socket server;
    private SpecialDrink special;
    private JPanel drinkPanel;

    /**
     * 
     * @param server
     * @param drinkPanel
     */
    public BartenderServer(Socket server, JPanel drinkPanel) {
		this.server = server;
		this.drinkPanel = drinkPanel;
    }
    /**
     * 
     */
    @Override
    public void run() {
        try {
		special = null;
		DrinkButton allButtons[] = new DrinkButton[8];
		for (int z = 0; z < 8; z++) {
			allButtons[z] = (DrinkButton) drinkPanel.getComponent(z);
		}
			// Get input from the client
			DataInputStream in = new DataInputStream(server.getInputStream());
			ObjectInputStream ois = new ObjectInputStream(in);
			PrintStream out = new PrintStream(server.getOutputStream());

			while ((special = (SpecialDrink) ois.readObject()) != null) {
			    for (int z = 0; z < 8; z++) {
				if (!allButtons[z].isButtonInUse()) {
				    for (int y = z + 1; y < 8; y++) {
					if (allButtons[y].isButtonInUse()) {
					    allButtons[z].setText(allButtons[y].getText());
					    allButtons[z].setBackground(Color.PINK);
					    allButtons[z].setButtonInUse(true);
					    allButtons[y].setButtonInUse(false);
					    allButtons[y].setBackground(Color.black);
					    y = 8;
					}
				    }
				}
			    }
			    for (int i = 0; i < 8; i++) {
				if (!allButtons[i].isButtonInUse()) {
				    System.out.println(special.getName());
				    System.out.println(special.getTableNumber());
				    allButtons[i].setFormattedText(special);
				    allButtons[i].setBackground(Color.PINK);
				    allButtons[i].setButtonInUse(true);
				    i = 8;
				}
			    }
			}
			server.close();
		    } catch (ClassNotFoundException ex) {
			Logger.getLogger(BartenderServer.class.getName()).log(Level.SEVERE, null, ex);
		    } catch (IOException ioe) {
		    }
    }
}